// components/Example.js
import React from 'react';
import { Upload, Icon, message } from 'antd';
import OSS from 'ali-oss';

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

const config = {
  region: 'oss-cn-beijing',
  accessKeyId: 'LTAITKK8IjV3akC7',
  accessKeySecret: 'JcSzxNgHeZqpxFyIRm7dUu2jJaniPO',
  bucket: 'mondora-test',
};
const client = new OSS(config);
const uploadPath = (path, file) => {
  // 上传文件的路径，使用日期命名文件目录
  return `${path}`;
};
const UploadToOss = (self, path, file) => {
  const url = uploadPath(path, file);
  console.log(123, url);
  const header = {
    'Content-Type': header,
  };
  return new Promise((resolve, reject) => {
    client.multipartUpload(url, file).then(data => {
      resolve(data);
    }).catch(error => {
      reject(error);
    });
  });
};

class Example extends React.Component {
  state = {
    loading: false,
  };
  handleChange = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl => this.setState({
        imageUrl,
        loading: false,
      }));
    }
  };
  beforeUpload = (file) => {
    // const isJPG = file.type === 'image/jpeg';
    // if (!isJPG) {
    //   message.error('You can only upload JPG file!');
    // }
    // const isLt2M = file.size / 1024 / 1024 < 2;
    // if (!isLt2M) {
    //   message.error('Image must smaller than 2MB!');
    // }
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = () => {
      // 使用ossupload覆盖默认的上传方法
      UploadToOss(this, 'mdl-business', file).then(data => {
        console.log(data.res.requestUrls);
        this.setState({ imageUrl: data.res.requestUrls });
      });
    };
    return false; // 不调用默认的上传方法
  };

  render() {
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'}/>
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    const imageUrl = this.state.imageUrl;
    return (
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        beforeUpload={this.beforeUpload}
        onChange={this.handleChange}
      >
        {imageUrl ? <img src={imageUrl} alt=""/> : uploadButton}
      </Upload>
    );
  }
}

export default Example;

